#include "mylibc.h"
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

myfile* myfopen(const char* filename,const char* mode)
{
    int fd=0,flag=0;
    if(strcmp(mode,"r")==0)
    {
        flag=O_RDONLY;
        fd=open(filename,O_RDONLY);
    }
    else if(strcmp(mode,"w")==0)
    {
        flag=O_CREAT|O_WRONLY|O_TRUNC;
        fd=open(filename,O_CREAT|O_WRONLY|O_TRUNC, 0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag=O_CREAT|O_WRONLY|O_APPEND;
        fd=open(filename,O_CREAT|O_WRONLY|O_APPEND, 0666);
    }

    myfile* my=(myfile*)malloc(sizeof(myfile));
    my->fileno=fd;
    my->flag=flag;
    my->bufferlen=0;
    my->flush_method=FLUSH_LINE;
    memset(my->buffer,0,sizeof(SIZE));

    return my;
}

int myfwrite(const char* ptr,size_t len,myfile* stream)
{
    memcpy(stream->buffer+stream->bufferlen,ptr,len);
    stream->bufferlen+=len;
    if(stream->flush_method==FLUSH_LINE && stream->buffer[stream->bufferlen-1]=='\n')
        myfflush(stream);
    return len;
}

void myfflush(myfile* stream)
{
    if(stream->bufferlen > 0)
    {
        write(stream->fileno,stream->buffer,stream->bufferlen);
        fsync(stream->fileno);
    }
    stream->bufferlen=0;
}

void myclose(myfile* stream)
{
    myfflush(stream);
    close(stream->fileno);
    free(stream);
}
